/*
Copyright (c) 2020 dxb22@163.com. All rights reserved.
*/

#include "http_wifi_config.h"
#include "http_server.h"
#include "lwip/sockets.h"
#include "utils_file.h"
#include "wlan.h"

const char *configPage = "<html><form method=\"POST\">SSID:<input name=\"ssid\"/><br/>PASSWORD:<input name=\"pw\" type=\"password\" /><br/><input type=\"submit\"/></form></html>";
const char *resultPage = "<html>%s<a href=\"/\">Click here back to index.</a></html>";

void GetRootPage(int fd, struct HttpRequest *req)
{
    (void)req;
    printf("%s:Reqeust setting page!\r\n", __func__);
    HttpResponse(fd, "%s", configPage);
}

void SetWifiPara(int fd, struct HttpRequest *req)
{
    printf("%s:Setting wifi!\r\n", __func__);
    char *contextType = GetHeaderValue(req, "Content-Type");
    if(contextType == NULL) {
        printf("%s:Get Content-Type failed!\r\n", __func__);
        return;
    }

    if(strcmp(contextType,"application/x-www-form-urlencoded") != 0) {
        printf("%s:Bad Context-Type received!Type=%s\r\n",__func__, contextType);
        return;
    }

    printf("%s:Content-Type:%s\r\n",__func__, contextType);
    char ssid[64] = "";
    char pw[32] = "";
    if(!GetFormPara(req, "ssid", ssid, sizeof(ssid))) {
        printf("%s:Get SSID failed!\r\n", __func__);
        return;
    }
    if(!GetFormPara(req, "pw", pw, sizeof(pw))) {
        printf("%s:Get PW failed!\r\n", __func__);
        return;
    }
    printf("Get SSID:%s\r\n", ssid);
    printf("Get PW:%s\r\n", pw);
    
    HttpResponse(fd, resultPage, "Connectting your configed AP! Device IP will display on LCD later.");
    free(contextType);
    contextType = NULL;
    SaveWifiSTAConfig(ssid,pw);
    InitWLan();
    ShutdownHttpServer();
}

int RunWifiConfigServer(void) {
    static struct RequestMapper httpRequestMapper[] = {
        {"GET /", GetRootPage},
        {"POST /", SetWifiPara}
    };
    return RunHTTPServer(httpRequestMapper, sizeof(httpRequestMapper) / sizeof(struct RequestMapper));
}